import unittest

from psychsim.pwl import *
from psychsim.action import Action,ActionSet
from psychsim.world import World,stateKey
from psychsim.agent import Agent
from psychsim.reward import *

''' 
This example tries faking a world step (the V attribute needs to be cleared or it doesn't work)
'''

class FalseStepsTestCase(unittest.TestCase):

    def setUp(self):
        #setup world, agent, and basics
        self.world = World()
        self.sammy = Agent('Sammy')
        self.world.addAgent(self.sammy)

        self.maxRounds=5
        self.world.setOrder(['Sammy'])

    def addStates(self):
        #define states
        self.world.defineState(None,'round',int)
        self.world.setState(None,'round',0)
        
        self.world.defineState('Sammy','energy',int)
        self.world.setState('Sammy','energy',10)
                    
    def addTermination(self):
        #terminate if maxRounds reached
        self.world.addTermination(makeTree({'if': thresholdRow(stateKey(None,'round'),self.maxRounds),
                                   True: True, False: False}))

    def addActions(self):
        #add actions and appropriate dynamics
        action =  self.sammy.addAction({'verb': 'do nothing'})
        tree = makeTree(incrementMatrix(stateKey(None,'round'),1))
        self.world.setDynamics('round',action,tree) 
        
        action =  self.sammy.addAction({'verb': 'do something'})
        tree = makeTree(incrementMatrix(stateKey('Sammy','energy'),-1))
        self.world.setDynamics(stateKey('Sammy','energy'),action,tree) 
        tree = makeTree(incrementMatrix(stateKey(None,'round'),1))
        self.world.setDynamics('round',action,tree) 

    def setModelAndRewards(self):
        #set model to update and Sammy's reward
        self.world.setModel('Sammy', True)
         
        self.sammy.setReward(minimizeFeature(stateKey('Sammy','energy')), 5., True)

    def testSetup(self):
        self.addStates()
        self.addTermination()
        self.addActions()
        self.setModelAndRewards()

    def testRun(self):
        self.testSetup()
        self.world.explain(self.world.step(real=False),level=3)
        self.world.agents['Sammy'].setReward(minimizeFeature(stateKey('Sammy','energy')), -5., True)
        self.world.agents['Sammy'].getAttribute('V',True).table = []
        self.world.explain(self.world.step(real=False),level=3)

if __name__ == "__main__":
    suite = unittest.TestSuite()
    for method in dir(FalseStepsTestCase):
       if method.startswith("test"):
          suite.addTest(FalseStepsTestCase(method))
    unittest.TextTestRunner().run(suite)
            